package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.SoulApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.PaperResult;
import com.tanhua.dubbo.pojo.PaperResultSimilarYou;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.server.vo.PaperResultVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class TestSoulService {

    @DubboReference(version = "1.0.0")
    private SoulApi soulApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @Value("${default.Similar}")
    private String defaultSimilar;

    public Object getPapers() {
        Long usesrId = UserThreadLocal.get();
        return this.soulApi.getPapers(usesrId);
    }

    public Object submitPaper(Map<String, Object> param) {
        Long userId = UserThreadLocal.get();
        return this.soulApi.submitPaper(param, Convert.toStr(userId));
    }

    public Object getResult(String id) {
        PaperResult paperResult = this.soulApi.getResult(id);
        PaperResultVo paperResultVo = BeanUtil.toBean(paperResult, PaperResultVo.class);

        Integer score = paperResult.getScore();
        List<Object> userIdList = this.soulApi.querySimilarUser(score, UserThreadLocal.get());

        Integer size = userIdList.size();

        if(size < 10) {
            String[] defaultSimilarList = defaultSimilar.split(",");
            for(int i = 0; i < 10 - size; i++) {
                userIdList.add(defaultSimilarList[i]);
            }
        }

        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);

        List<PaperResultSimilarYou> similarYouList = new ArrayList<>();

        for (UserInfo userInfo : userInfoList) {
            PaperResultSimilarYou similarYou = new PaperResultSimilarYou();
            similarYou.setId(Convert.toInt(userInfo.getUserId()));
            similarYou.setAvatar(userInfo.getLogo());
            similarYouList.add(similarYou);
        }
        paperResultVo.setSimilarYou(similarYouList);

        return paperResultVo;
    }
}
